package com.ums.core.service;

import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.Transaction;

import com.ums.core.common.db.HibernateSessionFactory;

public class BaseService {

	private static Session dbSession = null;
	private static Transaction dbTransaction = null; //can be used for TransactionContext
	private static boolean transactionRollback = false;
	
	public BaseService() {
			
		dbSession = HibernateSessionFactory.getSession();
	}
	
	protected Session getSession() {
		if(dbSession == null)
			dbSession = HibernateSessionFactory.getSession();
		return dbSession;
	}

	protected void begingTransaction() throws HibernateException {
		dbTransaction = dbSession.beginTransaction();
	}
	
	protected void endTransaction() {
		if(transactionRollback) {
			dbTransaction.rollback();
		} else {
			dbTransaction.commit();
		}
		dbTransaction = null;
	}
	
	protected void setTransactionRollback() {
		transactionRollback = true;
	}
	
	protected void closeSession() throws HibernateException {
		dbSession.flush();
		HibernateSessionFactory.closeSession();
	}
}
